﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ds.U6;
using DaInterFace;
using DaInterFace.UMode;
using System.Threading;
using System.Drawing;
using System.Data;

namespace DaSub.UMode
{
    public class UModeGate : IUModeGate
    {
        DsU6 _u6;
        DeviceInfo _di = new DeviceInfo();
        MeterInfoObject _meterInfo;
        Boolean _isOpen = false;
        Boolean _isReading = false;
        Boolean _allowRepeat = false;
        String _ip;
        EnumGateType _gateType;
        String _gateName;
        Boolean _forbidRepeat;
        IDataCenter _daCenter;
        String _iMessage;
        Font _font = new Font("宋体", 12.0f);
        int _failTimes = 0;
        String _typeName;
        Thread _mainThread;

        public event IMessageHandler IMessageEvent;

        public String GateName { get { return _gateName; } }
        public EnumGateType GateType { get {return _gateType;} }
        public MeterInfoObject MeterInfo { get { return _meterInfo; } }


        internal UModeGate(IDataCenter daCenter, String ip, EnumGateType gateType, String gateName, Boolean forbidRepeat)
        {
            _daCenter = daCenter;
            _ip = ip;
            _gateType = gateType;
            _gateName = gateName;
            _forbidRepeat = forbidRepeat;
            switch(gateType)
            {
                case EnumGateType.Ins: _typeName = "进厂"; break;
                case EnumGateType.Out: _typeName = "出厂"; break;        
            }
            _u6 = new DsU6(_ip, 20108);

            _mainThread = new Thread(Start);
            _mainThread.IsBackground = true;
            _mainThread.Name = "执行线程";
            _mainThread.Start();
        }

        private void IMessage(MessageType type, String iMessage)
        {
            _iMessage = iMessage;
            if (IMessageEvent != null)
            {
                IMessageEvent.Invoke(type, iMessage);
            }
        }

        private void Start()
        {
            while (true)
            {
                if (!_isOpen)
                {
                    Connect();
                }
                else
                {
                    Run();
                }

                if (_isOpen)
                {
                    Thread.Sleep(300);
                }
                else
                {
                    Thread.Sleep(3000);
                }
            }
        }

        private void Connect()
        {
            try
            {
                IMessage(MessageType.Note, "正在连接...");
                _u6.Open();
                _isOpen = _u6.IsPortOpen;
                if (_isOpen && _u6.Settings_SetRelay(SwitchEnum.No1, 3000) == DevResults.OK)
                {
                    _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁[{0}]，连接IP[{1}]成功", _gateName, _ip));
                    IMessage(MessageType.Note, _iMessage = "连接正常");
                }
                else
                {
                    IMessage(MessageType.Warning, "请检查U6跳线是否在1号线上。");
                }
            }
            catch (Exception ex)
            {
                IMessage(MessageType.Error, ex.Message);
            }
        }

        public void Dispose()
        {
            try
            {
                _mainThread.Abort();
                _mainThread = null;
               _u6.Close();
               _u6.Dispose();
            }
            catch(Exception)
            {
            
            }
        }

        private void Run()
        {
            if (_u6.Card_DeviceInfo(_di) == DevResults.OK)
            {
                if (_di.CardSerial == "" || _di.CardSerial == "00000000")
                {
                    if (_isReading)
                    {
                        _isReading = false;
                        _u6.Screen_ShowLogo();
                    }
                }
                else if (!_isReading)
                {
                    _isReading = true;
                    CheckInfo(_di.CardSerial);
                }
            }
            else
            {
                _failTimes++;
                if (_failTimes > 10)
                {
                    _isOpen = false;
                }
            }
        }

        public void Allow()
        {
            _u6.Switch_Open(SwitchEnum.No1, 3000);
            _u6.Screen_Print(3, 3, String.Format("请{0}", _typeName), _font);
        }

        public void Forbid()
        {
            _u6.Switch_Close(SwitchEnum.No1);
            _u6.Screen_Print(3, 3, String.Format("禁止{0}", _typeName), _font);
        }

        private Boolean CheckInfo(String serial)
        {
            Boolean right = false;
            StringBuilder sql = new StringBuilder();
            String uid = Guid.NewGuid().ToString();
            try
            {
                _meterInfo = _daCenter.DaData.GetMeterInfoByCardSerial(serial);
                if (_meterInfo.InfoEnable)
                {
                    switch (_meterInfo.Type)
                    {
                        case 5: 
                            Allow();
                            _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，允许{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                            break;
                        case 0: //销售
                            switch (_gateType)
                            {
                                case EnumGateType.Ins:
                                    switch (_meterInfo.Step)
                                    {
                                        case -1:
                                            sql.AppendFormat("EXEC KEW_SALES_CHECKREADJUST\r\n");
                                            sql.AppendFormat("EXEC KEW_SALES_SETNEWPRICE '{0}','{1}'\r\n", _meterInfo.BillID, _meterInfo.Item.ID);
                                            sql.AppendFormat("UPDATE KEW_SalesInfo SET FComboBox='1',FTime=GetDate() WHERE FID={0}\r\n", _meterInfo.BillID);
                                            sql.AppendFormat("EXEC KEW_SALES_LOG_INSERT {0},'{1} 刷卡进厂'\r\n", _meterInfo.BillID, _gateName);

                                            Recordset rs = _daCenter.DaData.ExeProcedure(_meterInfo.Base.Number, sql.ToString());
                                            if (rs.Enable)
                                            {
                                                Allow();
                                                _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，允许{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                                            }
                                            else
                                            {
                                                _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁:{0},{1}", _gateName, rs.Message));
                                                _u6.Screen_Print(0, 2, "系统异常", _font);
                                            }
                                            break;
                                        case 1:
                                            Allow();
                                            sql.AppendFormat("EXEC KEW_SALES_LOG_INSERT {0},'{1} 刷卡进厂'\r\n", _meterInfo.BillID, _gateName);
                                            _daCenter.DaData.ExeProcedure(_meterInfo.Base.Number, sql.ToString());
                                            _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，允许{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                                            break;
                                    }
                                    break;
                                case EnumGateType.Out:
                                    if (_meterInfo.Step == 3)
                                    {
                                        Allow();
                                        sql.AppendFormat("EXEC KEW_SALES_LOG_INSERT {0},'{1} 刷卡出厂'\r\n", _meterInfo.BillID, _gateName);
                                        _daCenter.DaData.ExeProcedure(_meterInfo.Base.Number, sql.ToString());
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，允许{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                                    }
                                    else
                                    {
                                        Forbid();
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，禁止{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                                    }
                                    break;
                            }
                            _u6.Screen_Print(0, 2, _meterInfo.CarNumber, _font);
                            break;
                        case 1: //采购
                            switch (_gateType)
                            { 
                                case EnumGateType.Ins:
                                    if (_meterInfo.IsLong && !_meterInfo.IsMetering)
                                    {
                                        sql.AppendFormat("EXEC KEW_PURCH_NEW '{0}','{1}','{2}','{3}','{4}','{5}','{6}'\r\n", _meterInfo.CarNumber, serial, 1, _meterInfo.SrcID, _meterInfo.QtyIpt, _gateName, uid);
                                        Recordset rs = _daCenter.DaData.ExeProcedure(_meterInfo.Base.Number, sql.ToString());
                                        if (rs.Enable)
                                        {
                                            if (Common.CBool(rs.Data.Tables[0].Rows[0][0].ToString()))
                                            {
                                                Allow();
                                                _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，允许{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                                                _daCenter.DaData.ExeProcedure(_meterInfo.Base.Number, String.Format("EXEC KEW_PURCH_LOG_INSERT {0},'{1}门禁刷卡进厂'", rs.Data.Tables[0].Rows[0][2].ToString(), _gateName));
                                            }
                                            else
                                            {
                                                Forbid();
                                                _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，异常:{1}", _gateName, rs.Data.Tables[0].Rows[0][1].ToString()));
                                                _u6.Screen_Print(0, 2, rs.Data.Tables[0].Rows[0][1].ToString(), _font);
                                            }
                                        }
                                        else
                                        {
                                            _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁:{0},{1}", _gateName, rs.Message));
                                            _u6.Screen_Print(0, 2, "系统异常", _font);
                                        }
                                    }
                                    else
                                    {
                                        if (_meterInfo.Step == 1)
                                        {
                                            Allow();
                                            _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，允许{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                                            sql.AppendFormat("EXEC KEW_PURCH_LOG_INSERT {0},'{1}门禁刷卡进厂'\r\n", _meterInfo.BillID, _gateName);
                                            _daCenter.DaData.ExeProcedure(_meterInfo.Base.Number, sql.ToString());
                                        }
                                        else
                                        {
                                            Forbid();
                                            _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，禁止{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                                        }
                                    }
                                    break;
                                case EnumGateType.Out:
                                    if (_meterInfo.Step == 3)
                                    {
                                        Allow();
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，允许{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                                        sql.AppendFormat("EXEC KEW_PURCH_LOG_INSERT {0},'{1}门禁刷卡出厂'\r\n", _meterInfo.BillID, _gateName);
                                        _daCenter.DaData.ExeProcedure(_meterInfo.Base.Number, sql.ToString());
                                    }
                                    else
                                    {
                                        Forbid();
                                        _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，禁止{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                                    }
                                    break;
                            }

                            _u6.Screen_Print(0, 2, _meterInfo.CarNumber, _font);
                            break;
                        case 2:
                            if ((_meterInfo.Step == 1 && _gateType == EnumGateType.Ins) || (_meterInfo.Step == 3 && _gateType == EnumGateType.Out))
                            {
                                Allow();
                                _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，允许{1}{2}", _gateName ,_meterInfo.CarNumber, _typeName));
                            }
                            else
                            {
                                Forbid();
                                _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，禁止{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                            }
                            _u6.Screen_Print(0, 2, _meterInfo.CarNumber, _font);
                            break;
                        case 3:
                            Allow();
                            _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁{0}，禁止{1}{2}", _gateName, _meterInfo.CarNumber, _typeName));
                            _u6.Screen_Print(0, 2, _meterInfo.CarNumber, _font);
                            break;
                    }
                }
                else
                {
                    _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁:{0},数据加载异常:{1}", _gateName, _meterInfo.UnEnableReason));
                    _u6.Screen_Print(0, 2, "系统异常", _font);
                }
            }
            catch (Exception ex)
            {
                _daCenter.DaUMode.Message(MessageType.Note, String.Format("门禁:{0},{1}", _gateName, ex.Message));
                _u6.Screen_Print(0, 2, "系统异常", _font);
            }

            return right;
        }
    }
}
